<template>
    <div class="commodity" :style="{ 'height': productsHeight }">
        <van-nav-bar :title="type" left-arrow @click-left="routerOutClick" />
        <searchHome v-model:value="queryParams.content" @onSubmit="onRefresh" :isFiltrate="false"/>
        <div class="commodity_classify">
            <div class="commodity_classify_item" @click="categoryIsShow = true">
                <span>{{ queryParams.categoryIdList.length ? '多品类' : '商品类目' }}</span>
                <img src="@/assets/commodity/icon_heisexiasanjiao.png" alt="">
            </div>
            <category :isShow="categoryIsShow" v-model:value="queryParams.categoryIdList" :multiple="true"
                @leftClick="categoryIsShow = false" @onSubmit="categorySubmit" />
        </div>
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh" :style="{ 'height': refreshHeight }">
            <van-list v-model:loading="loading" :finished="finished" @load="onLoad">
                <template v-slot:finished>
                    <div class="nothing_div" v-if="list.length == 0 && !refreshing">
                        <van-image :src="nothingData"></van-image>
                        <div class="nothing_font">暂无数据</div>
                    </div>
                </template>
                <van-swipe-cell v-for="item in list" :key="item.id">
                    <commodityList :data="item" @click="routerGo(item.productsId)" :names="names" />
                    <!-- <template #right>
                        <van-button v-if="item.shelvesStatus === 2" square type="danger" text="下架" style="height: 100%;"
                            @click="offShelf(item)" />
                        <van-button v-if="item.shelvesStatus !== 2" square type="success" text="上架"
                            style="height: 100%;" @click="grounding(item.productsId)" />
                        <van-button v-if="item.shelvesStatus === 2" square type="primary" text="出库"
                            style="height: 100%;" @click="outbound(item)" />
                    </template> -->
                </van-swipe-cell>
            </van-list>
        </van-pull-refresh>

        <van-overlay :show="overlayShow" @click="overlayShow = false" z-index="6001">
            <div class="wrapper" @click.stop>
                <div class="wrapper_div">
                    <van-image :src="colseImg" @click="close"></van-image>
                    <div class="title">下架原因</div>
                    <van-form @submit="onSubmit">
                        <van-field maxlength="200" show-word-limit v-model="message" rows="6" label="" type="textarea"
                            placeholder="请输入下架原因，不超过200字符" :border="false"
                            :rules="[{ required: true, trigger: 'onBlur', message: '请输入下架原因' }]" />
                        <van-button class="button" round block type="primary" native-type="submit" v-throttle:click>
                            提交确认
                        </van-button>
                    </van-form>
                </div>
            </div>
        </van-overlay>

    </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted, computed, onActivated } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { getEnvValue } from "@/utils/index";
import { setUpDownShelves, getTotalList, getOutTotalList } from '@/api/productHome/index'
import { showSuccessToast } from "vant";
const colseImg = new URL("@/assets/approval/close.png", import.meta.url).href;
// 类目
import category from '@/components/category/index.vue'
// 头部搜索框
import searchHome from '@/views/productHome/productLists/components/searchHome/index.vue'
// 列表
import commodityList from './commodityList.vue'

const names = ref('')
const nothingData = new URL("@/assets/porduct/icon_zanwushuju.png", import.meta.url).href
const route = useRoute();
/** 开始时间 */
const startTime = computed(() => {
    return route.query.startTime;
});
/** 结束时间 */
const endTime = computed(() => {
    return route.query.endTime;
});
/** 筛选类型 */
const type: any = computed(() => {
    return route.query.type;
});

const router = useRouter();
const overlayShow = ref(false)
const message = ref('')
const detailInfo = ref<any>({});
// 类目开关
const categoryIsShow = ref(false)

const refreshing = ref(false);
const loading = ref(false);
const finished = ref(false);
const list = ref<any>([]);
// 限制连续刷新数据重复问题
const refreFlag = ref(true)

// 查询列表参数
const queryParams = ref({
    content: '',
    categoryId: '',
    categoryName: '',
    pageSize: 10,
    pageNum: 1,
    categoryIdList: []
})

const productsHeight = ref()
const refreshHeight = ref()
const defaultPhoneHeight = ref(0) //屏幕默认高度
const nowPhoneHeight = ref(0) //屏幕现在的高度
const emits = defineEmits(['doShow'])
const vantListScrollTop = ref<any>(0) // 滚动位置

// 在组件挂载完成后添加事件监听器
onMounted(() => {
    defaultPhoneHeight.value = window.innerHeight;
    // 添加事件监听器
    window.addEventListener('resize', handleResize);
    functionScroll('init')
})
// 处理窗口大小变化的函数
const handleResize = () => {
    nowPhoneHeight.value = window.innerHeight;
};
// 在组件卸载前移除事件监听器
onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    functionScroll('delete')
});
watch(nowPhoneHeight, () => {
    if (defaultPhoneHeight.value != nowPhoneHeight.value) {
        // 当软键盘弹出,改变bottomIsSHow变量然后去控制bottom的显示与隐藏
        productsHeight.value = '100vh'
        refreshHeight.value = 'calc(100vh - 42.6666vw)'
        emits('doShow', false)
    } else {
        // 相等代表软键盘收起后,与上同理
        productsHeight.value = 'calc(100vh - 13.333333vw)'
        refreshHeight.value = 'calc(100vh - 56vw)'
        emits('doShow', true)
    }
})
// 获取列表数据
const getList = async () => {
    var res: any;
    if (['招商入库', '供应商入库', '还品入库'].includes(type.value)) {
        res = await getTotalList({
            ...queryParams.value,
            putStockType: type.value == '招商入库' ? 'E1' : type.value == '供应商入库' ? 'E3' : 'E2',
            putStartTime: startTime.value,
            putEndTime: endTime.value,
        })
        names.value = '入库数量'
    } else {
        res = await getOutTotalList({
            ...queryParams.value,
            outType: 1,
            putStartTime: startTime.value,
            putEndTime: endTime.value,
        })
        names.value = '出库数量'
    }
    // const { data } = await queryProductList(queryParams.value)
    const { rows = [], total = 0 } = res
    refreFlag.value = true
    // 空数据 停止加载
    if (rows.length == 0) {
        list.value = [];
        finished.value = true;
        return;
    }
    // 有数据 赋值列表 加载状态结束
    rows.forEach((item) => {
        finished.value = false;
        if (item.productImage) {
            item.productImages = getEnvValue("VITE_APP_PIC_URL") + item.productImage.split(',')[0];
        } else {
            item.productImages = "";
        }
        list.value.push(item);
    });
    loading.value = false;
    refreshing.value = false;
    // 如果list长度大于等于总数据条数，数据全部加载完成
    if (list.value.length >= total) {
        finished.value = true; //结束加载
    }
}

// 导航返回
const routerOutClick = () => {
    router.push({
        path: '/productHome',
        query: {
            startTime: startTime.value,
            endTime: endTime.value
        }
    })
}
// 跳转商品详情
const routerGo = (id) => {
    router.push({
        path: `/productHomeDetail/${id}`
    })
}

/** 加载更多 */
const onLoad = async () => {
    getList();
    queryParams.value.pageNum++;
};
/** 下拉 */
const onRefresh = () => {
    if (refreFlag.value) {
        refreFlag.value = false
        finished.value = false; // 清空列表数据
        refreshing.value = false;
        loading.value = true; // 加载状态
        queryParams.value.pageNum = 1; // 分页数赋值为1
        list.value = []; // 清空数组
        onLoad(); // 重新加载数据
    } else {
        finished.value = false;
        refreshing.value = false;
    }
};
// 商品类目选择完成
const categorySubmit = () => {
    categoryIsShow.value = false
    onRefresh()
}

/** 下架关闭 */
const close = () => {
    overlayShow.value = false
}
/** 下架建议提交 */
const onSubmit = async () => {
    await setUpDownShelves({
        stockProductsBoList: [
            {
                productsId: detailInfo.value.id,
                putType: 1, // 2上架 1下架
                offShelfRemark: message.value,
                locationCode: detailInfo.value.stockInfo.locationName,
                stockCode: detailInfo.value.stockCode
            }
        ]
    })
    showSuccessToast({ type: 'success', message: '下架成功' });
    overlayShow.value = false
    queryParams.value.pageNum = 1
    list.value = []
    onLoad();
    // router.back()
}
/** 缓存页面进度条 */
const functionScroll = (type: string) => {
    const dom: any = document.querySelector('.van-pull-refresh')
    if (type === 'init') {
        dom?.addEventListener('scroll', (e: any) => {
            vantListScrollTop.value = e.target.scrollTop
        })
    } else if (type === 'delete') {
        dom?.removeEventListener('scroll', () => { });
    } else if (type === 'black') {
        dom.scrollTop = vantListScrollTop.value
    }
}
onActivated(() => {
    functionScroll('black')
})
</script>
<script lang="ts">
export default { name: 'InventoryList' }
</script>

<style lang="less" scoped>
@import url(@/views/productHome/productLists/components//style/index.less);

.commodity {
    height: calc(100vh - 44px) !important;
    background-color: #f6faff;
}

:deep(.van-pull-refresh) {
    height: calc(100vh - 210px) !important;
    overflow: scroll;
}

.commodity_classify_item {
    width: 115px !important;
    flex: none !important;
}
</style>